package com.oswift.cms.web.backstage;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.oswift.cms.entity.FilesBean;
import com.oswift.cms.entity.PageBean;
import com.oswift.cms.entity.UploadBean;
import com.oswift.cms.entity.WebConfigBean;
import com.oswift.cms.service.IFilesService;
import com.oswift.cms.service.IPicService;
import com.oswift.cms.service.IWebConfigService;
import com.oswift.cms.utils.Field;
import com.oswift.cms.utils.PageCode;
import com.oswift.cms.utils.Field.Upload;
import com.oswift.utils.common.StringUtil;
import com.oswift.utils.common.TimeUtil;
import com.oswift.utils.exception.PlatException;
import com.oswift.utils.file.FileUtil;

@Controller
@RequestMapping("/security")
public class EditorAction extends BaseAction
{
    /**
     * 日志实例
     */
    private static Logger log = LoggerFactory.getLogger(EditorAction.class);

    /**
     * 每页显示记录条数
     */
    private static int PAGENUM = 50;

    /**
     * spring对象WebConfigService注入
     */
    @Resource
    private IWebConfigService webConfigService;

    /**
     * PicServiceImpl注入对象
     */
    @Resource
    private IPicService picService;

    /**
     *
     * spring 注入
     */
    @Resource
    private IFilesService filesService;

    /**
     *
     * 上传图片
     *
     * @author zhuou
     */
    @RequestMapping(value = "/editorUploadImg", method = RequestMethod.POST)
    @ResponseBody
    public String uploadImg(HttpServletRequest request)
    {
        String json = "";
        try
        {
            UploadBean uploadBean = picService.uploadImg(request, this
                    .getAdmin(request).getCompanyID());

            if (PageCode.COMMON_SUCCESS.equals(uploadBean.getState()))
            {
                json = toJsonString(Upload.SUCCESS, uploadBean
                        .getOriginalName(), uploadBean.getOriginalName(),
                        uploadBean.getRelativePath());
            }
            else if (PageCode.UPLOAD_IMG_ISEMPTY.equals(uploadBean.getState()))
            {
                json = toJsonString(Upload.NOFILE, "", "", "");
            }
            else if (PageCode.IMG_TYPE_ERROR.equals(uploadBean.getState()))
            {
                json = toJsonString(Upload.TYPE, "", "", "");
            }
            else if (PageCode.CREATE_FOLDER_FAIL.equals(uploadBean.getState()))
            {
                json = toJsonString(Upload.DIR, "", "", "");
            }
            else
            {
                json = toJsonString(Upload.UNKNOWN, "", "", "");
            }
        }
        catch (Exception e)
        {
            json = toJsonString(Upload.UNKNOWN, "", "", "");
        }

        return json;
    }

    /**
     *
     * 图片管理页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/editorManagerImg")
    @ResponseBody
    public Object editorManagerImg(HttpServletRequest request)
    {
        PageBean<FilesBean> pageBean = null;
        try
        {

            int pageNum = DEFAULT_PAGENUM;
            String nowPage = request.getParameter("nowPage");
            if (!StringUtil.isEmpty(nowPage))
            {
                pageNum = Integer.valueOf(nowPage);
            }
            pageBean = filesService.getFiles(this.getAdmin(request)
                    .getCompanyID(), null, Field.Files.IMG, PAGENUM, pageNum);
            if (null == pageBean)
            {
                pageBean = new PageBean<FilesBean>();
                pageBean.setPageRecordNum(0);
                pageBean.setTotalRecordNum(0);
                pageBean.setDataList(new ArrayList<FilesBean>());
            }
        }
        catch (PlatException e)
        {
            log.error("The method of editorManagerImg is system's error.", e);
            pageBean = new PageBean<FilesBean>();
            pageBean.setPageRecordNum(0);
            pageBean.setTotalRecordNum(0);
            pageBean.setDataList(new ArrayList<FilesBean>());
        }

        return pageBean;
    }

    @RequestMapping(value = "/editorUploadFile", method = RequestMethod.POST)
    @ResponseBody
    public Object editorUploadFile(HttpServletRequest request)
    {
        UploadBean uploadBean = new UploadBean();
        try
        {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

            MultipartFile fileFile = multipartRequest.getFile("upfile");

            // 保存图片
            if (null == fileFile.getOriginalFilename()
                    || "".equals(fileFile.getOriginalFilename()))
            {
                uploadBean.setState(Upload.NOFILE);
                return uploadBean;
            }

            String fileName = fileFile.getOriginalFilename();

            // 获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名
            String ext = fileName.substring(fileName.lastIndexOf(".") + 1,
                    fileName.length());

            // 对扩展名进行小写转换
            ext = ext.toLowerCase();

            // 判断上传的类型是否符合容许上传文件类型
            String fileExt = Upload.DEFAULT_UPLOADFILE_TYPE;

            // 查询出配置
            WebConfigBean webBean = webConfigService.getWebConfigById(getAdmin(
                    request).getSiteId());
            if (null != webBean
                    && !StringUtil.isEmpty(webBean.getUploadFileType()))
            {
                fileExt = webBean.getUploadFileType();
            }
            String[] imgExts = fileExt.split(Upload.FILE_SEPARATOR);
            List<String> fileExtList = new ArrayList<String>();
            for (String s : imgExts)
            {
                fileExtList.add(s.toLowerCase());
            }

            // 判断是否符合要求
            if (!fileExtList.contains(ext))
            {
                uploadBean.setState(Upload.TYPE);
                return uploadBean;
            }

            // 获取当前时间，文件命名需要
            Date date = new Date();

            // 文件路径
            StringBuilder path = new StringBuilder();

            // 相当路径
            StringBuilder contextPath = new StringBuilder();
            contextPath.append(request.getContextPath());
            path.append(request.getSession().getServletContext()
                    .getRealPath(""));

            // 文件路径分隔符
            contextPath.append(Upload.URL_SEPARATOR);
            path.append(FileUtil.FILE_SEPARATOR);

            contextPath.append(Upload.UPLOAD_ROOT_FILENAME);
            path.append(Upload.UPLOAD_ROOT_FILENAME);

            // 文件路径分隔符
            contextPath.append(Upload.URL_SEPARATOR);
            path.append(FileUtil.FILE_SEPARATOR);

            // 单位Id，作为存储每个用户文件的路径
            int companyId = getAdmin(request).getCompanyID();
            contextPath.append(companyId);
            path.append(companyId);

            // 文件路径分隔符
            contextPath.append(Upload.URL_SEPARATOR);
            path.append(FileUtil.FILE_SEPARATOR);

            // 存储图片的文件夹
            contextPath.append(Upload.UPLOAD_FILE_FILENAME);
            path.append(Upload.UPLOAD_FILE_FILENAME);

            // 文件路径分隔符
            contextPath.append(Upload.URL_SEPARATOR);
            path.append(FileUtil.FILE_SEPARATOR);

            // 按月存储图片文件
            String folder = TimeUtil.dateToString(date,
                    TimeUtil.COMPACT_DATE_FORMAT);
            contextPath.append(folder);
            path.append(folder);

            // 新建文件夹，如果父文件夹不存在，遍历新建
            boolean isSuccess = FileUtil.createDirectory(path.toString());

            // 失败直接返回
            if (!isSuccess)
            {
                uploadBean.setState(Upload.DIR);
                return uploadBean;
            }

            // 文件路径分隔符
            contextPath.append(Upload.URL_SEPARATOR);
            path.append(FileUtil.FILE_SEPARATOR);

            // 定义图片新名称
            String newName = TimeUtil.dateToString(date,
                    TimeUtil.COMPACT_DATE_TIME_MS_FORMAT)
                    + '.' + ext;
            contextPath.append(newName);
            path.append(newName);

            // 保存
            File img = new File(path.toString());
            fileFile.transferTo(img);

            // uploadBean.setState(Upload.SUCCESS);
            // uploadBean.setOriginal(fileName);
            // uploadBean.setTitle(fileName);
            // uploadBean.setUrl(contextPath.toString());
        }
        catch (Exception e)
        {
            uploadBean.setState(Upload.UNKNOWN);
        }

        return uploadBean;
    }

    /**
     *
     * 递归查询文件夹下的图片
     *
     * @author zhuou
     * @param realpath
     *            路径
     * @param files
     *            文件对象
     * @return List
     */
    public List<File> getImgs(String realpath, List<File> files)
    {
        File realFile = new File(realpath);
        if (realFile.isDirectory())
        {
            File[] subfiles = realFile.listFiles();
            for (File file : subfiles)
            {
                if (file.isDirectory())
                {
                    getImgs(file.getAbsolutePath(), files);
                }
                else
                {
                    files.add(file);
                }
            }
        }

        return files;
    }

    /**
     *
     * 拼接json
     *
     * @author zhuou
     * @return String
     */
    private String toJsonString(String state, String original, String title,
            String url)
    {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append("\"state\":");
        sb.append("\"");
        sb.append(state);
        sb.append("\"");
        sb.append(Field.COMMA);

        sb.append("\"original\":");
        sb.append("\"");
        sb.append(original);
        sb.append("\"");
        sb.append(Field.COMMA);

        sb.append("\"title\":");
        sb.append("\"");
        sb.append(title);
        sb.append("\"");
        sb.append(Field.COMMA);

        sb.append("\"url\":");
        sb.append("\"");
        sb.append(url);
        sb.append("\"");

        sb.append("}");
        return sb.toString();
    }

    public void setWebConfigService(IWebConfigService webConfigService)
    {
        this.webConfigService = webConfigService;
    }

    public void setPicService(IPicService picService)
    {
        this.picService = picService;
    }

    public void setFilesService(IFilesService filesService)
    {
        this.filesService = filesService;
    }
}
